import React from "react";
import { useDispatch, useSelector } from "react-redux";
import ListItem from "../../components/ListItem";
import { RootState } from "../../store";
import { Checkbox, Stepper, SubmitBar } from "react-vant";
import {
  addCarCountActionCreator,
  subCarCountActionCreator,
  switchCarStateActionCreator,
  switchCarStateAllActionCreator,
} from "../../store/car/car";
import { useNavigate } from "react-router-dom";

const Index: React.FC = () => {
  const car = useSelector((state: RootState) => state.car.car);
  const navigate = useNavigate()
  // 总价钱
  const totalPrice = car
    .filter((v) => v.state)
    .reduce((p, n) => {
      return p + n.count * n.price;
    }, 0);
  // 全选
  const totalState = car.every((v) => {
    return v.state;
  });

  const dispatch = useDispatch();

  return (
    <div className="car">
      {car.map((v, i) => {
        return (
          <ListItem
            key={i}
            v={v}
            preLeft={
              <Checkbox
                checked={v.state}
                onChange={() => dispatch(switchCarStateActionCreator(v))}
              ></Checkbox>
            }
            desc={
              <Stepper
                min={1}
                value={v.count}
                onPlus={() => dispatch(addCarCountActionCreator(v))}
                onMinus={() => dispatch(subCarCountActionCreator(v))}
              ></Stepper>
            }
          ></ListItem>
        );
      })}
      <SubmitBar
        price={totalPrice * 100}
        buttonText="提交订单"
        onSubmit={() => navigate('/order', { state: { price: totalPrice } })}
      >
        <Checkbox
          checked={totalState}
          onChange={(checked) =>
            dispatch(switchCarStateAllActionCreator(checked))
          }
        >
          全选
        </Checkbox>
      </SubmitBar>
    </div>
  );
};

export default Index;
